/**
 * 测试赤壁玩法获胜者接口 (act_id: 5281)
 * 测试文件：test-chibi-winners.js
 */

const WebSocket = require('ws');

// 测试配置
const config = {
    wsUrl: 'ws://localhost:3000/user-service/websocket',
    testData: {
        act_id: 5281,
        d: {
            pageNum: 0
        }
    }
};

// 测试赤壁获胜者查询
async function testChibiWinners() {
    console.log('🚀 开始测试赤壁玩法获胜者接口...');

    return new Promise((resolve, reject) => {
        const ws = new WebSocket(config.wsUrl);

        ws.on('open', () => {
            console.log('✅ WebSocket连接已建立');

            // 发送查询请求
            const request = {
                c: config.testData.act_id,
                d: config.testData.d
            };

            console.log('📤 发送请求:', JSON.stringify(request, null, 2));
            ws.send(JSON.stringify(request));
        });

        ws.on('message', (data) => {
            try {
                const response = JSON.parse(data.toString());
                console.log('📥 收到响应:', JSON.stringify(response, null, 2));

                // 验证响应格式
                if (response.act_id === config.testData.act_id) {
                    if (response.code === 0) {
                        console.log('✅ 接口调用成功');

                        // 验证数据结构
                        if (response.data && Array.isArray(response.data.list)) {
                            console.log(`✅ 数据格式正确，共 ${response.data.total} 条记录`);
                            console.log(`✅ 当前页: ${response.data.page}`);
                            console.log(`✅ 每页大小: ${response.data.pageSize}`);
                            console.log(`✅ 是否有更多: ${response.data.hasMore}`);

                            // 显示前几条记录
                            if (response.data.list.length > 0) {
                                console.log('\n📊 前3条获胜记录:');
                                response.data.list.slice(0, 3).forEach((winner, index) => {
                                    console.log(`  ${index + 1}. 用户ID: ${winner.userId}, 角色ID: ${winner.characterId}`);
                                    console.log(`     支援国家: ${winner.side} (${getSideName(winner.side)})`);
                                    console.log(`     下注: ${winner.betGold}金 + ${winner.betSilver}银`);
                                    console.log(`     中奖: ${winner.winGold}金 + ${winner.winSilver}银`);
                                    console.log(`     收益率: ${winner.profitRate}%`);
                                    console.log(`     期数: ${winner.roundId}`);
                                    console.log('');
                                });
                            } else {
                                console.log('ℹ️  暂无获胜记录');
                            }
                        } else {
                            console.log('❌ 响应数据结构不正确');
                        }
                    } else {
                        console.log(`❌ 接口调用失败，错误码: ${response.code}`);
                        if (response.msg) {
                            console.log(`❌ 错误信息: ${response.msg}`);
                        }
                    }
                }

                // 关闭连接
                ws.close();
                resolve(response);

            } catch (error) {
                console.error('❌ 解析响应数据失败:', error);
                ws.close();
                reject(error);
            }
        });

        ws.on('error', (error) => {
            console.error('❌ WebSocket连接错误:', error);
            reject(error);
        });

        ws.on('close', () => {
            console.log('🔌 WebSocket连接已关闭');
        });

        // 设置超时
        setTimeout(() => {
            console.log('⏰ 请求超时');
            ws.close();
            reject(new Error('请求超时'));
        }, 10000);
    });
}

// 获取国家名称
function getSideName(side) {
    const sideNames = {
        1: '魏国',
        2: '蜀国',
        3: '吴国'
    };
    return sideNames[side] || '未知';
}

// 测试分页功能
async function testChibiWinnersPagination() {
    console.log('\n🔄 测试分页功能...');

    for (let page = 0; page < 3; page++) {
        console.log(`\n📄 测试第 ${page} 页:`);

        try {
            const response = await testChibiWinnersWithPage(page);

            if (response.code === 0 && response.data) {
                console.log(`✅ 第 ${page} 页: 共 ${response.data.list.length} 条记录`);
                console.log(`   总记录数: ${response.data.total}`);
                console.log(`   是否有更多: ${response.data.hasMore}`);
            }

            // 等待一下再测试下一页
            await new Promise(resolve => setTimeout(resolve, 1000));

        } catch (error) {
            console.error(`❌ 第 ${page} 页测试失败:`, error.message);
        }
    }
}

// 测试指定页数的获胜者查询
async function testChibiWinnersWithPage(page) {
    return new Promise((resolve, reject) => {
        const ws = new WebSocket(config.wsUrl);

        ws.on('open', () => {
            const request = {
                c: config.testData.act_id,
                d: { pageNum: page }
            };

            ws.send(JSON.stringify(request));
        });

        ws.on('message', (data) => {
            try {
                const response = JSON.parse(data.toString());
                ws.close();
                resolve(response);
            } catch (error) {
                ws.close();
                reject(error);
            }
        });

        ws.on('error', (error) => {
            ws.close();
            reject(error);
        });

        setTimeout(() => {
            ws.close();
            reject(new Error('请求超时'));
        }, 5000);
    });
}

// 主测试函数
async function runTests() {
    try {
        console.log('🎯 赤壁玩法获胜者接口测试开始\n');

        // 测试基本功能
        await testChibiWinners();

        // 测试分页功能
        await testChibiWinnersPagination();

        console.log('\n🎉 所有测试完成！');

    } catch (error) {
        console.error('\n💥 测试过程中发生错误:', error.message);
    }
}

// 如果直接运行此文件，则执行测试
if (require.main === module) {
    runTests();
}

module.exports = {
    testChibiWinners,
    testChibiWinnersPagination,
    runTests
};
